using System;

namespace Beeflys
{
    abstract class AResponsiveSponsor : ISponsor
    {
        public AResponsiveSponsor(TimeSpan timeout)
        {
            this.onTimeoutEvent = this.OnTimeoutEvent;

            this.timer = SponsorTimer.Get(timeout);
            this.timer.RegisterTimeoutEvent(this.onTimeoutEvent);

            this.timer.Start(timeout);
        }

        private ISponsorTimer timer;
        private Action onTimeoutEvent;

        private void OnTimeoutEvent()
        {
            this.timer.RemoveTimeoutEvent(this.onTimeoutEvent);

            this.OnResponseReturn(null, ActorOpencode.TIMEOUT);
        }

        public void Respond(object o, ActorOpencode opencode)
        {
            if(this.timer.Completed)
            {
                Logger.Current.Warn("请求已经超时，已经做超时返回，本次return无效");
                return;
            }
            
            this.timer.RemoveTimeoutEvent(this.onTimeoutEvent);
            this.timer.Stop();

            this.OnResponseReturn(o, opencode);
        }

        protected abstract void OnResponseReturn(object o, ActorOpencode opencode);
    }
}
